package com.ywjt.platformbusiness.store.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.adapter.SortingCenterAdapter;
import com.ywjt.platformbusiness.store.order.model.SortingCenterModel;
import com.ywjt.platformbusiness.store.order.model.StoreOrderListModel;
import com.ywjt.platformbusiness.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SortingCenterActivity  extends BaseActivity  {
    private static final int REQUEST_CODE = 101;
    private RecyclerView rcCommon;
    private SortingCenterAdapter adapter;
    private String lat="";
    private String lng="";
    private StoreOrderListModel.ResultDTO.RecordsDTO orderModel;
    private LinearLayout llNodata;

    private String status="1";//1 默认正常 2 带值


    public static void actionStart(Context context,StoreOrderListModel.ResultDTO.RecordsDTO orderModel,String status) {
        Intent intent = new Intent(context, SortingCenterActivity.class);
        intent.putExtra("orderModel",(Serializable) orderModel);
        intent.putExtra("status",status);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.goods_type_fragment;
    }

    @Override
    protected void initView() {
        setTitleText("分拣中心列表");
        status=getIntent().getStringExtra("status");
        orderModel=(StoreOrderListModel.ResultDTO.RecordsDTO)getIntent().getSerializableExtra("orderModel");
        rcCommon=findViewById(R.id.rcCommon);
        llNodata=findViewById(R.id.llNodata);


        //checkPermission();

        lat="113.784208";
        lng="34.758762";
        getData();
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }

    //获取订单详情
    public void getData(){
        new HttpRequest(getContext()).doGet(UrlConstants.logistics_getDistance+lat+","+lng, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), SortingCenterModel.class);
                        if (obj instanceof SortingCenterModel) {
                            SortingCenterModel model=(SortingCenterModel)obj;

                            if (model.getResult().size()>0){
                                rcCommon.setVisibility(View.VISIBLE);
                                llNodata.setVisibility(View.GONE);
                                rcCommon.setLayoutManager(new LinearLayoutManager(SortingCenterActivity.this));
                                adapter=new SortingCenterAdapter(model.getResult());
                                rcCommon.setAdapter(adapter);
                                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        if (status.equals("1")){
                                            MailGoodsDetailActivity.actionStart(SortingCenterActivity.this,model.getResult().get(position),orderModel);
                                        }else if (status.equals("2")){
                                            Intent intent = new Intent();
                                            intent.putExtra("sortCenter",(Serializable)model.getResult().get(position));
                                            setResult(RESULT_OK, intent);
                                            finish();
                                        }
                                    }
                                });
                            }else {
                                llNodata.setVisibility(View.VISIBLE);
                                rcCommon.setVisibility(View.GONE);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(SortingCenterActivity.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    lat=amapLocation.getLatitude()+"";
                    lng=amapLocation.getLongitude()+"";
                    getData();
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public void initLocation(){

//初始化定位
        mLocationClient = new AMapLocationClient(SortingCenterActivity.this);
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    initLocation();
                } else {
                    Toast.makeText(SortingCenterActivity.this, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }


    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(SortingCenterActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PermissionChecker.PERMISSION_GRANTED||
                        PermissionChecker.checkSelfPermission(SortingCenterActivity.this,Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions((Activity) SortingCenterActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    },REQUEST_CODE);
                }else {
                    initLocation();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
